define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀

    angular.module('ContractIncome', ['ContractCommonService'])
        .filter('sumIncomeAmount', function () {
            return function (incomes) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.amount));
                });
                return amount;
            }
        })
        .filter('remainIncomeAmount', function () {
            return function (incomes, contract) {
                var amount = 0;
                $.each(incomes, function (i, d) {
                    if (d['__type'] == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, parseFloat(d.amount));
                });
                if (contract) {
                    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                        //云客签约-直属区域/云客签约-联营区域
                        //收入金额汇总 = 签约金额
                        return myMath.sub(contract.sign_amount, amount);
                    } else {
                        //其他：收入金额汇总=结算金额
                        return myMath.sub(contract.balance_amount, amount);
                    }

                }

                return 0;
            }
        })
        .filter('signOrBalanceAmount', function () {
            return function (contract) {
                if (contract) {
                    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                        //云客签约-直属区域/云客签约-联营区域
                        //收入金额汇总 = 签约金额
                        return contract.sign_amount;
                    } else {
                        //其他：收入金额汇总=结算金额
                        return contract.balance_amount;
                    }
                }
                return 0;
            }
        })
        .filter('signOrBalanceLabel', function () {
            return function (contract) {
                if (contract) {
                    if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                        || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                        //云客签约-直属区域/云客签约-联营区域
                        //收入金额汇总 = 签约金额
                        return '签约金额';
                    } else {
                        //其他：收入金额汇总=结算金额
                        return '结算金额';
                    }
                }
                return 0;
            }
        })
        .filter('saveEnabled', function () {
            return function (incomes) {
                return $.grep(incomes, function (d, i) {
                    return d.editMode == 1 || d.editMode == 2;
                }).length;
            }
        })
        .controller('contractIncomeCtrl', ['$scope', '$routeParams', 'contractCommonService', function ($scope, $routeParams, contractCommonService) {
            var contractId = $routeParams.id;

            // 合同签署公司下拉框处理
            $scope.ddlConfigCompany = {
                allowClear: false,
                data: [{id: 1, text: '明源云客'}],
                placeholder: '账套公司'
            };

            //获取合同信息
            contractCommonService.getContract(contractId, function (data) {
                if(data){
                    //获取公司下拉信息
                    contractCommonService.actionGetContractAccountCompanyList(data.contract.contract_property_id, function (data2) {
                        var ddlData = [];
                        $.each(data2, function (i, d) {
                            ddlData.push({id: d.account_company_id, text: d.account_company_name});
                        });
                        $scope.ddlConfigCompany.data = ddlData;
                        $scope.contractBaseInfo = data.contract;
                        $scope.$applyAsync();

                    });


                }

            });

            //收入类别
            $scope.ddlConfigIncomeCategory = {
                allowClear: false,
                data: [],
                placeholder: '核算收入类别',
                onchange2: function (newVal, scope) {
                    if (scope) {
                        scope.type_name = newVal.text;
                    }
                }
            };
            //获取核算收入类别下拉信息
            contractCommonService.getBussAccountTypes(function (data) {
                var ddlData = [];
                $.each(data, function (i, d) {
                    ddlData.push({id: d.type_id, text: d.type_name});
                });
                $scope.ddlConfigIncomeCategory.data = ddlData;
                $scope.$applyAsync();
            });

            //收入信息
            $scope.incomes = [];
            $scope.revenueInfo = {};

            //获取收入
            contractCommonService.getContractRevenue(contractId, function (data) {
                $scope.revenueInfo = data;
                $scope.incomes = data.revenueList;
                $scope.$applyAsync();
            });

            $scope.addIncome = function () {
                /**
                 * 新增收入
                 */
                $scope.incomes.push({editMode: 1, __type: 'add', amount: 0});
            };
            $scope.editIncome = function (item) {
                /**
                 * 编辑收入
                 * @type {number}
                 */
                    //先保存原始数据
                item.orginalData = angular.copy(item);
                item.editMode = 2;
            };
            $scope.editIncomeOk = function (item) {
                /**
                 * 保存收入信息
                 * @type {number}
                 */
                if (!item.revenue_type) {
                    util.alert('核算收入类别不能为空');
                    return;
                }

                if(item.amount == null){
                    util.alert('收入金额不能为空');
                    return;
                }
                if(!item.amount.toString().match(/^[\d]*(\.[\d]+)*$/ig)){
                    util.alert('收入金额必须为大于等于0的数值');
                    return;
                }

                if (!parseFloat(item.amount)) {
                    util.alert('收入金额必须为大于等于0的数值');
                    return;
                }

                if (item.ddl2Category) {
                    item.categoryName = item.ddl2Category.text;
                }

                item.editMode = 0;
            };

            $scope.editIncomeCancel = function (item, idx) {
                /**
                 * 取消保存
                 * @type {number}
                 */

                if (item.editMode == 1) {
                    $scope.incomes.splice(idx, 1);
                } else {
                    angular.extend(item, item.orginalData);
                    item.editMode = 0;
                }

            };

            $scope.delIncome = function (item) {
                /**
                 * 删除收入
                 * @type {number}
                 */

                util.confirm('确定要删除此收入吗？', {
                    ok: function () {
                        angular.extend(item, {__type: 'delete'});
                        $scope.$applyAsync();
                    }
                });
            };

            $scope.save = function () {
                /**
                 * 保存收入信息
                 */

                var baseInfo = $scope.contractBaseInfo;
                var incomesInfo = $scope.incomes;

                var post_data = {
                    contractId: contractId,
                    revenueList: incomesInfo,
                    accountCompanyId: baseInfo.account_company_id
                };
                var url = api_prefix + "/contract/submit-revenue";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function (json) {
                        if (json.retCode === "0") {
                            $.each($scope.incomes, function(i, d){
                                if(d.__type=='add'){
                                    d.__type='edit';
                                }
                            })

                            util.alert('保存成功');
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            }
        }]);
});